capture program drop distIVboundsmonotone


program distIVboundsmonotone 
	syntax varlist(min=2) , d(varlist) z(varlist) [mean variance quantile(real .5)]
	
	dis in red "Estimation using instrument exogeneity and non-negative treatment effects"
	
	gettoken Y X:varlist
 
 	*generating influence functions and their upper and lower bounds
	*********preparation of estimation - this is independent of IV vs panel, and of regression method******** 
	generateIF Y, `mean' `variance' quantile(`quantile')
	*generating upper and lower bounds on potential outcome influence functions
	***imposing monotonicity of treatment effects
	tempname IF1upper IF1lower IF0upper IF0lower
	quietly gen `IF1upper' = D*IF + (1-D)*IFupper
	quietly gen `IF1lower' = IF   
			*because the counterfactual IF is bounded by the actual
	quietly gen `IF0upper' = IF   
			*same
	quietly gen `IF0lower' = (1-D)*IF + D*IFlower
	************************************************************************
	
	
	*******running regressions to estimate bounds on gphi******************************
	***assumes: we have binary instrument Z, positively correlated with D, exogenous given X
	tempname ASF1upper ASF1lower ASF0upper ASF0lower
	
	quietly regress `IF1upper' `X' if (Z==1)
	predict `ASF1upper', xb
	quietly regress `IF1lower' `X' if (Z==1)
	predict `ASF1lower', xb

	quietly regress `IF0upper' `X' if (Z==0)
	predict `ASF0upper', xb
	quietly regress `IF0lower' `X' if (Z==0)
	predict `ASF0lower', xb

	gen gphiupper=max(`ASF1upper'-`ASF0lower',0)
	gen gphilower=max(`ASF1lower'-`ASF0upper',0)
		*because the ATE is bounded by 0
	gen w=gphiupper-gphilower
	*****************************************************
	sum w
	
end
